const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
app.listen(3000);

// 中间件
app.use('/static', express.static(path.join(__dirname, 'static')));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// 引入并使用mysql模块
const mysql = require('mysql');
let con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    port: 3306,
    database: 'demo'
})
con.connect();

// 渲染页面
app.get('/login', (req, res) => {
    res.sendFile(path.join(__dirname, '登录.html'))
})

// 登录逻辑
app.post('/login', (req, res, next) => {
    let { tel, pass } = req.body;
    console.log(tel, pass);
    // 传参不能为空
    if (!tel || !pass) {
        next('请输入有效内容');
        return;
    }
    let is = `SELECT * FROM 已有用户 WHERE username='${tel}' and password='${pass}'`;
    con.query(is, (err, result) => {
        
        if (result.length > 0) {
            next('登录成功')
            return;
        }else{
            next('账号或密码有误')
            return;
        }
    })

})
app.use((err, req, res, next) => {
    res.send({ code: 400, msg: err })
})